<template>
    <div class="name-search-container">
        <h2>姓名查询系统</h2>
        <div class="search-box">
            <input v-model="searchKeyword" type="text" placeholder="请输入姓名或拼音关键词" @input="handleSearch" />
            <button @click="handleSearch">查询</button>
        </div>

        <div class="results" v-if="results.length > 0">
            <h3>查询结果 (共 {{ results.length }} 条)</h3>
            <ul>
                <li v-for="(person, index) in results" :key="index">
                    {{ person.name }} - {{ person.department }} - {{ person.position }}
                </li>
            </ul>
        </div>

        <div class="no-results" v-else-if="hasSearched">
            未找到匹配的姓名
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import PinyinMatch from "pinyin-match";

// 搜索关键词
const searchKeyword = ref('');
// 查询结果
const results = ref<any[]>([]);
// 是否已执行查询
const hasSearched = ref(false);

// 模拟姓名数据
const personData = [
    { name: '张三', department: '技术部', position: '前端工程师' },
    { name: '李四', department: '产品部', position: '产品经理' },
    { name: '王五', department: '市场部', position: '市场专员' },
    { name: '赵六', department: '技术部', position: '后端工程师' },
    { name: '钱七', department: '财务部', position: '财务分析师' },
    { name: '孙八', department: '人力资源部', position: 'HR专员' },
    { name: '周九', department: '技术部', position: 'UI设计师' },
    { name: '吴十', department: '运营部', position: '运营经理' }
];

// 处理查询
const handleSearch = () => {
    if (!searchKeyword.value.trim()) {
        results.value = [];
        hasSearched.value = false;
        return;
    }

    const keyword = searchKeyword.value.trim();

    // 使用pinyin-match进行拼音匹配
    results.value = personData.filter(person => {
        return PinyinMatch.match(person.name, keyword);
    });

    hasSearched.value = true;
};

</script>

<style scoped>
.name-search-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: Arial, sans-serif;
}

h2 {
    text-align: center;
    color: #333;
    margin-bottom: 30px;
}

.search-box {
    display: flex;
    margin-bottom: 20px;
}

.search-box input {
    flex: 1;
    padding: 10px 15px;
    font-size: 16px;
    border: 1px solid #ddd;
    border-radius: 4px 0 0 4px;
}

.search-box button {
    padding: 10px 20px;
    font-size: 16px;
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
}

.search-box button:hover {
    background-color: #40a9ff;
}

.results {
    margin-top: 20px;
}

.results h3 {
    color: #333;
    margin-bottom: 15px;
}

.results ul {
    list-style: none;
    padding: 0;
}

.results li {
    padding: 12px;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 10px;
    background-color: #f9f9f9;
}

.no-results {
    text-align: center;
    padding: 40px;
    color: #999;
}
</style>